package com.polaris.live.viewmodel.home

import androidx.lifecycle.MutableLiveData
import com.blankj.utilcode.util.CollectionUtils
import com.polaris.live.common.constant.CommonConst
import com.polaris.live.common.mvvm.viewmodel.BaseViewModel
import com.polaris.live.common.network.request
import com.polaris.live.common.network.state.ResultState
import com.polaris.live.net.homeService
import com.polaris.live.resp.back_resp.ListWithBannerBean
import com.polaris.live.resp.base.ListResp
import com.polaris.live.resp.base.new
import com.polaris.live.widget.refresh.OnListListener
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope

/**
 * CommunityRecommendViewModel
 *
 * @author Created by 半仙 on 2024/9/4/004 20:26
 */
class CommunityRecommendViewModel : BaseViewModel(), OnListListener {

    val mListLiveData = MutableLiveData<ResultState<ListResp<Any>>>()

    private fun communityRecommend(position: Int) {
        request({
            if (position == 0) {
                coroutineScope {
                    val listResp = async { homeService.getHotList(position) }.await()
                    val bannerResp =
                        async { homeService.getBannerListV2(CommonConst.BannerType.BANNER_HOME) }.await()

                    val list = listResp.result?.list?.toMutableList<Any>()?.apply {
                        add(0, ListWithBannerBean(bannerResp.result?.banner ?: emptyList()))
                    } ?: emptyList()

                    if (CollectionUtils.isEmpty(bannerResp.result?.banner)) {
                        listResp.new(listResp.result?.list)
                    } else {
                        listResp.new(list)
                    }
                }
            } else {
                homeService.getHotList(position).let { it.new(it.result?.list) }
            }
        }, mListLiveData)
    }

    override fun onRefresh() {
        communityRecommend(0)
    }

    override fun onLoadMore(pageIndex: Int) {
        communityRecommend(pageIndex)
    }

}